import { View, Image, Text, CoverImage, RichText } from '@tarojs/components'
import { useState, useEffect, useCallback } from 'react'
import LgInput from '../../components/input'
import LgCell from '../../components/cell'
import Header from '../../components/navCustomBar'
// import Header from '@/pages/myComponent/header'
import Taro from '@tarojs/taro'
import moment from 'moment'
import { requestSystemUrl } from 'src/network/baseUrl'
import { HttpGet } from '../../../network/servers'
import Utils from '../../../utils/index'
import { connect } from 'react-redux'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '../../components/utils';
import { CalendarPicker, List, Popup, VirtualInput, Input, Modal } from 'antd-mobile'
import '../../images/public/style.css'
import './index.scss'

const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const storage = getStorage()
var wx = require('weixin-js-sdk')
const {
  getNowToken,
  getQueryVariable,
} = Utils


function App(props) {

  let {
    baseUrl,
  } = props

  const getToken = () => {
    if (getQueryVariable('env') == 'weapp') {
      return getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || getQueryVariable('lg_tk')
    }
  }


  const [detail, setDetail] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [imgList, setImgList] = useState([]);

  const [newsId, setNewsId] = useState("");

  const [isRead, setIsRead] = useState(0);
  const [height, setHeight] = useState(0);

  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [cover, setCover] = useState('')
  //2023
  const [typeList, setTypeList] = useState([])
  const [visible, setVisible] = useState(false)
  const [typeId, setTypeId] = useState('')
  const [typeName, setTypeName] = useState('')

  const [toEdu, setToEdu] = useState(false)

  const getCommonData = () => {
    if (Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram') {
      // 小程序端的h5
      if (!baseUrl) {
        // 直接跳转当前页面

      } else {
        console.log('小程序');

        //应用内跳转
        let instance = Taro.getCurrentInstance()
        if (instance.router?.params) {
          let params = instance.router.params
          let id = params.id
          if (!id) return;
          // console.log(params);
          setIsRead(isRead)
          setNewsId(id)

          let url = "/api/news/info//edit/detailed"
          HttpGet({
            url,
            data: {
              newsId: id,
            }
          }).then(res => {
            if (res.code == 200 && res.data) {
              let data = res.data
              console.log(data.newsCoverPath, 'data.newsCoverPath');

              setTitle(data.newsTitle)
              // setContent((data.newsContent).replace(/<[^>]*>|<\/[^>]*>/gm, ""))
              setContent(data.newsContent)
              setCover(JSON.parse(JSON.stringify(data.newsCoverPath)))
              setTypeId(data.newsTypeId)
              setTypeName(data.newsTypeName)
              let attachments = res.data.newsAttachmentVoList
              if (attachments && attachments.length !== 0) {
                let imgArr = [], fileArr = [];
                attachments.map(item => {
                  let fileType = Utils.getFileType(item?.attachmentName)
                  if (fileType == 'img') {
                    item.url = item.attachmentUrl
                    item.size = item.attachmentSize
                    item.fileName = item.attachmentName
                    imgArr.push(item)
                  } else {
                    item.url = item.attachmentUrl
                    item.size = item.attachmentSize
                    item.fileName = item.attachmentName
                    fileArr.push(item)
                  }
                })

                setFileList(fileArr)
                setImgList(imgArr)
              }
              setIsRead(res.data.readStatus)
              setDetail(res.data)
            } else {
              Taro.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      }
    } else {
      // app内 1.应用内跳转(不需要获取通知地址和用户信息) 2.直接跳转
      let instance = Taro.getCurrentInstance()

      const browserController = getBrowserController()
      let height = browserController.getStatusBarHeight()
      setHeight(height)
      if (instance.router?.params) {
        let params = instance.router.params
        let id = params.id
        if (!id) return;
        // console.log(params);

        setIsRead(isRead)
        setNewsId(id)

        HttpGet({
          // url: '/api/commons/school/user/self',
          url: `api/common/user`,
          data: {
            token: getNowToken()
          },

        }).then((res1) => {
          HttpGet({
            // url: 'api/commons/system/server/info',
            url: 'api/common/system/list',
            data: {
              sysIds: '220',
            },
          }).then((response) => {
            let url = response.data.webSvrAddr + "/api/news/info//edit/detailed"
            HttpGet({
              url,
              data: {
                newsId: id,
              }
            }).then(res => {
              if (res.code == 200 && res.data) {
                let data = res.data
                console.log(data.newsCoverPath, 'data.newsCoverPath');

                setTitle(data.newsTitle)
                // setContent((data.newsContent).replace(/<[^>]*>|<\/[^>]*>/gm, ""))
                setContent(data.newsContent)
                setCover(JSON.parse(JSON.stringify(data.newsCoverPath)))
                setTypeId(data.newsTypeId)
                setTypeName(data.newsTypeName)
                let attachments = res.data.newsAttachmentVoList
                if (attachments && attachments.length !== 0) {
                  let imgArr = [], fileArr = [];
                  attachments.map(item => {
                    let fileType = Utils.getFileType(item?.attachmentName)
                    if (fileType == 'img') {
                      item.url = item.attachmentUrl
                      item.size = item.attachmentSize
                      item.fileName = item.attachmentName
                      imgArr.push(item)
                    } else {
                      item.url = item.attachmentUrl
                      item.size = item.attachmentSize
                      item.fileName = item.attachmentName
                      fileArr.push(item)
                    }
                  })

                  setFileList(fileArr)
                  setImgList(imgArr)
                }
                setIsRead(res.data.readStatus)
                setDetail(res.data)
              } else {
                Taro.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          })
        })
      }
    }
  }

  const [detail_data, setDetail_data] = useState({})
  //获取详情数据
  const getDetailData = () => {
    console.log(props)
    let params = props.tid.split('?')[1]
    params = params.split('&')[0].split('=')[1]
    console.log(params)
    let url = 'api/weekly/general/info/detail'
    HttpGet({
      url,
      data: {
        weeklyRoutineId: params,
      }
    }).then((res) => {
      if (res.code == 200) {
        let data = res.data
        let arr: any[] = []
        data.generalWeeklyPlanVoList.forEach(i => {
          if (arr.length == 0) {
            arr.push({
              planDate: i.planDate.slice(0, 10),
              saveWeeklyPlanBoList: [{
                departmentId: i.departmentId,
                departmentName: i.departmentName,
                planContent: i.planContent,
                time: i.time,
                place: i.place
              }]
            })
          } else {
            let isSameTime = false
            let tempObj1 = {}
            let index
            arr.forEach((i2, index2) => {
              console.log(i2.planDate)
              console.log(i.planDate.slice(0, 10))
              if (i2.planDate == i.planDate.slice(0, 10)) {
                tempObj1 = {
                  departmentId: i.departmentId,
                  departmentName: i.departmentName,
                  planContent: i.planContent,
                  time: i.time,
                  place: i.place
                }
                index = index2
                isSameTime = true
              } else {
                tempObj1 = i
              }
            })
            if (isSameTime) {
              arr[index].saveWeeklyPlanBoList.push(tempObj1)
            } else {
              arr.push({
                planDate: tempObj1.planDate.slice(0, 10),
                saveWeeklyPlanBoList: [{
                  departmentId: tempObj1.departmentId,
                  departmentName: tempObj1.departmentName,
                  planContent: tempObj1.planContent,
                  time: tempObj1.time,
                  place: tempObj1.place

                }]
              })
            }
          }
        })
        console.log(arr)
        res.data.list = arr
        setDetail_data(res.data)
      }
    })
  }

  const goBack = () => {
    Taro.navigateBack()
    // Taro.redirectTo({
    //   url: '/pages/newsInfoApp/index'
    // })
    console.log(Utils.getQueryVariable('isManage'))
    if (Utils.getQueryVariable('isManage')) {
      Taro.redirectTo({
        url: `/pages/newsInfoApp/index?lg_tk=${storage.get('token')}&isManage=1`
      })
    } else {
      Taro.redirectTo({
        url: `/pages/newsInfoApp/index?lg_tk=${storage.get('token')}`
      })
    }
  }

  const initWxSdk = async () => {
    const params = getWxSDKParams(['previewImage', 'getLocation'])
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log('ready')
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log(res)
    });
  }

  useEffect(() => {
    // document.title = '添加周行事历'
    document.title = '周行事历详情'
    if (window.__wxjs_environment == 'miniprogram') {
      initWxSdk()
    }
    getCommonData()
    getDetailData()
    return () => {
      if (Utils.getSystemInfo() == 'weapp') {
        document.title = '周行事历详情'
        window.getNoticeList && typeof window.getNoticeList == 'function' && window.getNoticeList()
      }
    }
  }, []);

  const publishEdu = () => {
    setToEdu(!toEdu);
  }

  const [visible2, setVisible2] = useState(false)

  const [time_val, setTime_val] = useState('')

  const [gap_day, setGap_day] = useState([])

  // 编辑按钮
  const [nowBeSelectPlan, setNowBeSelectPlan] = useState({})
  const [popupVisible, setPopupVisible] = useState(false)
  const [temp_saveWeeklyPlanBoList, setTemp_saveWeeklyPlanBoList] = useState([])
  const changePopupVisible = (index) => {
    setPopupVisible(!popupVisible)
    let tempData = gap_day[index]
    setNowBeSelectPlan(gap_day[index])
    if (gap_day[index].saveWeeklyPlanBoList.length <= 0) {
      setTemp_saveWeeklyPlanBoList([{
        departmentName: '',
        planContent: ''
      }])
    } else {
      setTemp_saveWeeklyPlanBoList(gap_day[index].saveWeeklyPlanBoList)
    }
    console.log(gap_day[index])
  }

  const showDetailContent = (content) => {
    console.log(content)
    const modal = Modal.show({
      content: <div>
        <div style={{ textAlign: "center" }}>
          <span className='detailDepartment'>{content.departmentName}</span>
        </div>
        <div className='detailContent'>
          <span style={{ color: "rgb(153,153,153)" }}>事务安排：</span><span>{content.planContent}</span>
        </div>
        <div className='detailContent'>
          <span style={{ color: "rgb(153,153,153)" }}>时间：</span><span>{content.time}</span>
        </div>
        <div className='detailContent'>
          <span style={{ color: "rgb(153,153,153)" }}>地点：</span><span>{content.place}</span>
        </div>
        <div style={{ marginTop: "36px", height: "1px", width: "100%", backgroundColor: "rgba(153,153,153,0.3)" }}></div>
        <div
          style={{ textAlign: "center", color: "rgb(0,153,255)", marginTop: "14px" }}
          onClick={() => {
            modal.close(); // 关闭弹窗
          }}
        >
          确定
        </div>
      </div>,
      closeOnMaskClick: true,
    });
  }

  const showDetailTitle = () => {
    Modal.show({
      content: <div>
        <div>
          <span className='detailDepartment'>标题</span><span>{detail_data.title}</span>
        </div>
      </div>,
      closeOnMaskClick: true,
    })
  }


  return (
    <View className="newsTitle">
      {
        Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram' ?
          "" :
          <Header
            className='header-top'
            mainTitle='周行事历详情'
            mainTitleBlod={false}
            isTitlePositionLeft={true}
            needMainIcon={process.env.TARO_ENV == 'weapp' ? false : true}
            onClick={Taro.getCurrentInstance().router?.params.from ? goBack : ''}
          />
        // <Header
        //   title='周行事历详情'
        //   isLeft={true}
        //   isBlod={false}
        // />
      }

      <View className="header">
        <View className='select_type'>
          <LgCell
            title={<Text><Text className='must-fill'></Text><span style={{ color: '#999999' }}>所属分区</span></Text>}
            content={
              <div style={{ color: '#333333', fontSize: '16px' }}>{detail_data?.partitionName}</div>
            }
            type='A'
          ></LgCell>
        </View>
        <View className="line"></View>
        <div onClick={() => { showDetailTitle() }}>
          <LgCell
            title={<Text><Text className='must-fill'></Text><span style={{ color: '#999999' }}>标题</span></Text>}
            content={
              <div style={{ color: '#333333', fontSize: '16px' }}>{detail_data.title?.length >= 15 ? detail_data.title.slice(0, 14) + '...' : detail_data.title}</div>
            }
            type='A'
          ></LgCell>
        </div>
        <View className="line"></View>

        <div>
          <LgCell
            title={<Text><Text className='must-fill'></Text><span style={{ color: '#999999' }}>起止时间</span></Text>}
            content={
              <div style={{ color: '#333333', fontSize: '16px' }}>{`${detail_data.startDate?.slice(0, 10).replaceAll('-', '/')}-${detail_data.endDate?.slice(0, 10).replaceAll('-', '/')}`}</div>
            }
            type='A'
          ></LgCell>
        </div>

        <div className='line2'></div>

        <View>
          <div className='table_title'>事务安排
            {
              detail_data.generalWeeklyPlanVoList?.length > 0 ? <span>(共<span style={{ color: 'rgb(51,51,51)' }}>{detail_data.generalWeeklyPlanVoList.length}</span>项)</span> : ''
            }
          </div>
          {
            detail_data.generalWeeklyPlanVoList?.length > 0 ? <>
              <div className='table_detail_box'>
                <div className='table_header'>
                  <div className='time'>时间</div>
                  <div className='arrange'>事务安排</div>
                  {/* <div className='operation'>操作</div> */}
                </div>
                <div className='table_list' style={{ maxHeight: '57vh' }}>
                  {
                    detail_data.list?.length > 0 ? <>
                      {
                        detail_data.list.map((i, index) => {
                          return (
                            <div className='table_item'>
                              <div className='table_item_time'>{`${i.planDate.slice(5, 7)}月${i.planDate.slice(8)}日`}
                              <div style={{color: "rgb(153,153,153)"}}>({ weekdays[new Date(moment(i.planDate).format("yyyy-MM-DD")).getDay()]})</div>
                              </div>
                              <div className='table_item_arrange'>
                                {
                                  i.saveWeeklyPlanBoList.length > 0 ? <>
                                    {
                                      i.saveWeeklyPlanBoList.map(i2 => {
                                        return (
                                          <div className='arrange_item' onClick={() => { showDetailContent(i2) }}>
                                            <div className='content1'>
                                              <div className='department'>{i2.departmentName}</div>
                                              <div className='arrange_content'>{i2?.planContent ? i2.planContent.length < 8 ? i2.planContent : i2.planContent.slice(0,8) + "..." : '--'}</div>
                                            </div>
                                            <div className='content2'>
                                              <div>时间：{i2?.time ? i2.time : '--'}</div>
                                              <div className='place'>地点：{i2?.place ? i2.place.length < 8 ? i2.place : i2.place.slice(0,8) + "..." : '--'}</div>
                                            </div>
                                          </div>
                                        )
                                      })
                                    }
                                  </> : <div className='arrange_item'></div>
                                }
                              </div>
                              <div className='table_item_operation2'></div>
                            </div>
                          )

                        })
                      }
                    </> : ''
                  }
                </div>
              </div>
            </> : <div className='empty'>
              <div className='empty_img'></div>
              <div className='empty_text'>请选择起止时间</div>
            </div>
          }
        </View>

      </View>
    </View>
  )
}

const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl,
    systemInfo1: commonData.systemInfo,
  }
}

export default connect(mainProps)(App);
